#!/usr/bin/perl -w

# Modified to also look for 8.x.x as well as 0.7.x!!!

BEGIN {
	push @INC,"/usr/local/cluster/lib/perl";
}

use clutils;
use strict;

# exit codes
# 1 - unable to open directory /usr/src/cluster [linuxha incorrectly installed?]
# 2 - drbd is not yet loaded!
# 3 - unable to query drbd version

$::ARG_verbose=1;
$::D="/usr/src/cluster";
$::M=undef;

if(! -f "/proc/drbd") {
	system("/sbin/modprobe drbd 2>/dev/null");
	if(! -f "/proc/drbd") {
		exit 2;
	}
}
open(FD,"/proc/drbd") or exit 3;
$::cline=<FD>; close(FD);
system("/sbin/rmmod drbd 2>/dev/null");
($::V)=($::cline =~ /version: (0.7.\d+|8\.\d+\.\d+) \(/);
if(! defined($::V) || $::V eq "") {
	exit 3;
}

sub vcompare($$) {
my ($a,$b)=@_;

	my @a2=split(/\./,$a);
	my @b2=split(/\./,$b);
	while(1) {
		if($a2[0] < $b2[0]) {
			return -1;
		}
		if($a2[0] > $b2[0]) {
			return 1;
		}
		shift @a2;
		shift @b2;
		last if !@a2 || !@b2;
	}
	return 0;
}

# $::V is the currnet module version in the x.x.x format

# Scan the /usr/src/cluster directory for later code revisions

opendir(DFD,$::D) or exit 1;
{
my $x;
my $x2;

	while($x=readdir(DFD)) {
		if($x =~ /^drbd-(\d+\.\d+\.\d+)\.tar.gz$/) {
			my $nv=$1;
			if(vcompare($nv,$::V)>0) {
				if(defined($x2)) {
					if(vcompare($nv,$x2)>1) {
						$::M=$nv;
						$x2=$nv;
					}
				} else {
					$::M=$nv;
					$x2=$nv;
				}
			}
		}		
	}
	closedir(DFD);
}

if(defined($::M)) {
	print "drbd-$::M.tar.gz\n";
}

exit 0;
